import React from 'react';
import { View, PanResponder, Dimensions } from 'react-native';
import styles from './styles';

const totalWidth = Dimensions.get('window').width;

class Flex extends React.Component {
  constructor(props) {
    super(props);
    this.watcher = null;
    this.startX = 0;
    this.state = {
       leftPoint: 1,
    }
    this.onPanResponderGrant = this.onPanResponderGrant.bind(this);
    this.onPanResponderMove = this.onPanResponderMove.bind(this);
    this.onPanResponderEnd = this.onPanResponderEnd.bind(this);
  }

  componentWillMount() {
    this.watcher = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: this.onPanResponderGrant,
      onPanResponderMove: this.onPanResponderMove,
      onPanResponderEnd: this.onPanResponderEnd,
    });
  }
  static navigationOptions = {
    title: '手势操作',
    text: '',
  };
  onPanResponderGrant(e, gestureState) {
    this.startX = gestureState.x0;
  }
  onPanResponderMove(e,gestureState) {
    let leftPoint;
    if (gestureState.moveX < this.startX) {
      leftPoint = 1;
    } else {
      if (gestureState.moveX > totalWidth - 42  - 48 + this.startX) {
        leftPoint =  totalWidth - 42  - 48;
      } else {
        leftPoint = gestureState.moveX - this.startX;
      }
    }
    this.setState(()=>{
      return {leftPoint};
    });
  }

  onPanResponderEnd(e, gestureState) {
    const leftPoint = 1;
    this.setState(()=>{
      return {leftPoint};
    });
  }

  onSwitchChange = (event) => {
    this.setState({
      aSwitch: !this.state.aSwitch,
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.barViewStyle}>
          <View style={[styles.buttonViewStyle, {left: this.state.leftPoint}]}
           {...this.watcher.panHandlers}
          />
        </View>
      </View>
    )
  }
}

export default Flex;
